package com.skcc.ngms.matest;

import java.io.File;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.telephony.TelephonyManager;

/**
 * 인증 유틸리티
 * 
 * @author : june
 * @date : $Date$
 * @id : $Id$
 */
public class AuthUtil {

	public static String B_COMPANY_CODE = null;

	public static final String ID_MDN = "MDN";
	public static final String ID_APP_ID = "APPID";

	public static final String ID_AUTH_KEY = "authKey";
	public static final String ID_COMPANY_CD = "companyCd";
	public static String ID_ENC_PWD = "encPwd";
	public static String ENC_PWD_VALUE = null;
	
	public static final String APP_ID = "Z000S01020";
	public static final String PRIMITIVE = "NMP_SKCC_COMMON";
	public static String GROUPCODE = "SK";
	public static String LANG = "ko";
	public static String AUTH_INFO;

	public static Context mContext = null;

	public static void GMPAuth(Context context) throws Exception {
		if (context == null) {
			throw new Exception();
		}

		mContext = context;
		ContentValues values = new ContentValues();

		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		if (tm == null) {
			throw new Exception();
		}

		values.put(ID_MDN, tm.getLine1Number());
		values.put(ID_APP_ID, APP_ID);
		ContentResolver cr = context.getContentResolver();
		Uri uri = cr.insert(Uri.parse("content://com.skt.pe.auth/GMP_AUTH"),
				values);
		List<String> authValues = uri.getPathSegments();
		String returnId = authValues.get(1);
		String appVer = context.getPackageManager().getPackageInfo(
				context.getPackageName(), 0).versionName;
		if ("E001".equals(returnId)) {
			throw new Exception("E001_GMP_AUTH is null!");
		} else if ("E002".equals(returnId)) {
			throw new Exception("E002_GMP_AUTH is fail!");
		}
		String[] gmpAuth = null;
		String buffer = authValues.get(2);
		gmpAuth = buffer.split("\\|");

		Map<String, String> gmpAuthPwd = getGMPAuthPwd(context,
				tm.getLine1Number(), APP_ID);

		ENC_PWD_VALUE = gmpAuthPwd.get("encPwd");

		AUTH_INFO = "appId=" + APP_ID 
				+ "&primitive=" + PRIMITIVE
				+ "&mdn=" + tm.getLine1Number()
				+ "&authKey=" + URLEncoder.encode(gmpAuth[0]) 
				+ "&appVer=" + appVer 
				+ "&encPwd=" + ENC_PWD_VALUE
				+ "&companyCd="+ URLEncoder.encode(gmpAuth[1]) 
				+ "&groupCd=" + GROUPCODE
				+ "&lang=" + LANG ;
		
	}

	/**
	 * GMP 로그인 화면을 띄운다. (일반 로그인) 호출하는 activity로 결과를 리턴한다. 로그인 성공 : RESULT_OK,
	 * 로그인 취소 : 303, 나머지 RESULT_CANCEL
	 * 
	 * 
	 * @param activity
	 *            호출하는 activity
	 */
	public static void runGMPLogin(Activity activity) {
		Intent intent = new Intent("com.sk.pe.group.auth.GMP_LOGIN");
		activity.startActivityForResult(intent, 400);
	}

	/**
	 * Legacy 로그인 화면을 띄운다. (겸직 로그인)
	 * 
	 * @param activity
	 */
	public static void runLegacyLogin(Activity activity, String companyCd) {
		Intent intent = new Intent("com.sk.pe.group.auth.LEGACY_LOGIN");
		intent.putExtra("COMPANY_CD", companyCd);
		activity.startActivityForResult(intent, 1007);
	}

	/**
	 * 로그아웃
	 * 
	 * @param context
	 * @throws Exception
	 */
	public static void logout(Context context) throws Exception {
		ContentResolver cr = context.getContentResolver();
		cr.update(Uri.parse("content://com.skt.pe.auth"), new ContentValues(),
				null, null);
	}

	/**
	 * 서비스 요청에 필요한 authKey, companyCd를 얻는다. 각각 해당 키값은 ID_AUTH_KEY(="authKey"),
	 * ID_COMPANY_CD(="companyCd")
	 * 
	 * @param context
	 * @param mdn
	 * @param appId
	 * @return
	 * @throws Exception
	 */
	public static Map<String, String> getGMPAuth(Context context, String mdn,
			String appId) throws Exception {
		ContentValues values = new ContentValues();
		values.put(ID_MDN, mdn);
		values.put(ID_APP_ID, appId);

		ContentResolver cr = context.getContentResolver();
		Uri uri = cr.insert(Uri.parse("content://com.skt.pe.auth/GMP_AUTH"),
				values);
		List<String> authValues = uri.getPathSegments();
		String returnId = authValues.get(1);

		if ("E001".equals(returnId)) {
			throw new Exception("E001"); // GMP_AUTH is null!
		} else if ("E002".equals(returnId)) {
			throw new Exception("E002"); // GMP_AUTH is fail!
		}

		// android.util.Log.d("GMP_AUTH_RESULT", returnId);

		String[] gmpAuth = null;
		String buffer = authValues.get(2);
		gmpAuth = buffer.split("\\|");

		Map<String, String> map = new HashMap<String, String>();

		String[] ids = new String[] { ID_AUTH_KEY, ID_COMPANY_CD };
		for (int i = 0; i < gmpAuth.length; i++) {
			map.put(ids[i], gmpAuth[i]);
		}

		return map;
	}

	/**
	 * 서비스 요청에 필요한 authKey, companyCd, encPwd를 얻는다. 각각 해당 키값은
	 * ID_AUTH_KEY(="authKey"), ID_COMPANY_CD(="companyCd"),
	 * ID_ENC_PWD(="encPwd")
	 * 
	 * @param context
	 * @param mdn
	 * @param appId
	 * @return
	 * @throws Exception
	 */
	public static Map<String, String> getGMPAuthPwd(Context context,
			String mdn, String appId) throws Exception {
		ContentValues values = new ContentValues();
		values.put(ID_MDN, mdn);
		values.put(ID_APP_ID, appId);

		ContentResolver cr = context.getContentResolver();
		Uri uri = cr.insert(
				Uri.parse("content://com.skt.pe.auth/GMP_AUTH_PWD"), values);
		List<String> authValues = uri.getPathSegments();
		String returnId = authValues.get(1);

		if ("E001".equals(returnId)) {
			throw new Exception("E001"); // GMP_AUTH is null!
		} else if ("E002".equals(returnId)) {
			throw new Exception("E002"); // GMP_AUTH is fail!
		} else if ("E007".equals(returnId)) {
			throw new Exception("E007"); // GMP_AUTH is fail!
		} else if ("E008".equals(returnId)) {
			throw new Exception("E008"); // LEGACY is fail!"
		}

		Map<String, String> map = new HashMap<String, String>();

		String buffer = authValues.get(2);
		String[] ids = new String[] { ID_AUTH_KEY, ID_COMPANY_CD, ID_ENC_PWD };

		// 구분자가 포함된 암호화된 패스워드가 나올 수 있음
		int b_offset = 0;
		int offset = buffer.indexOf("|");
		if (offset != -1) {
			map.put(ids[0], buffer.substring(0, offset));

			b_offset = offset;
			offset = buffer.indexOf("|", offset + 1);
			if (offset != -1) {
				map.put(ids[1], buffer.substring(b_offset + 1, offset));
				map.put(ids[2], buffer.substring(offset + 1));
			} else {
				throw new Exception("E999");
			}
		} else {
			throw new Exception("E999");
		}

		return map;
	}

	/**
	 * 비밀키를 얻는다.
	 * 
	 * @param context
	 * @return
	 * @throws Exception
	 */
	public static String getSecretKey(Context context) throws Exception {
		ContentResolver cr = context.getContentResolver();
		Uri uri = cr.insert(Uri.parse("content://com.skt.pe.auth/SECRETKEY"),
				new ContentValues());
		List<String> authValues = uri.getPathSegments();
		String returnId = authValues.get(1);

		if ("E001".equals(returnId)) {
			throw new Exception("E001"); // Secret-Value is null!
		}
		return authValues.get(2);
	}

	/**
	 * Nonce값을 얻는다.
	 * 
	 * @param context
	 * @return
	 * @throws Exception
	 */
	public static String getNonce(Context context) throws Exception {
		ContentResolver cr = context.getContentResolver();
		Uri uri = cr.insert(Uri.parse("content://com.skt.pe.auth/NONCE"),
				new ContentValues());
		List<String> authValues = uri.getPathSegments();
		String returnId = authValues.get(1);

		if ("E001".equals(returnId)) {
			throw new Exception("E001"); // "Nonce-Value is null!"
		}

		return authValues.get(2);
	}

	/**
	 * 현재 선택된 회사코드를 얻는다.
	 * 
	 * @param context
	 * @return
	 * @throws Exception
	 */
	public static String getCheckedCompanyCd(Context context) throws Exception {
		ContentResolver cr = context.getContentResolver();
		Uri uri = cr.insert(
				Uri.parse("content://com.skt.pe.auth/CHECKED_COMPANY_CD"),
				new ContentValues());
		List<String> authValues = uri.getPathSegments();
		String returnId = authValues.get(1);

		if ("E001".equals(returnId)) {
			throw new Exception("E001"); // CheckedCompanyCd-Value is null!
		}

		return authValues.get(2);
	}

	/**
	 * 자회사를 포함한 겸직회사 코드 및 명을 얻는다.
	 * 
	 * @param context
	 * @return
	 * @throws Exception
	 */
	public static Map<String, String> getCompanyList(Context context)
			throws Exception {
		ContentResolver cr = context.getContentResolver();
		Uri uri = cr.insert(
				Uri.parse("content://com.skt.pe.auth/COMPANY_LIST"),
				new ContentValues());
		List<String> authValues = uri.getPathSegments();
		String returnId = authValues.get(1);

		if ("E001".equals(returnId)) {
			throw new Exception("E001"); // CompanyList-Value is null!
		}

		// 한글의 공백 때문에 추가적으로 decode를 함
		String buffer = URLDecoder.decode(authValues.get(2));
		String[] company = buffer.split("\\|");

		Map<String, String> companyMap = new LinkedHashMap<String, String>();
		for (int i = 0; i < company.length; i = i + 2) {
			companyMap.put(company[i], company[i + 1]);
		}

		return companyMap;
	}

	/**
	 * nonce값을 수정한다.
	 * 
	 * @param context
	 * @param nonce
	 */
	public static void updateNonce(Context context, String nonce) {
		ContentResolver cr = context.getContentResolver();
		ContentValues cv = new ContentValues();
		cv.put("NONCE", nonce);
		cr.update(Uri.parse("content://com.skt.pe.auth"), cv, null, null);
	}

	/**
	 * 선택된 회사코드를 수정한다.
	 * 
	 * @param context
	 * @param companyCd
	 * @param mdn
	 * @param appId
	 * @throws Exception
	 */
	public static void updateCheckedCompanyCd(Context context,
			String companyCd, String mdn, String appId) throws Exception {
		B_COMPANY_CODE = getCheckedCompanyCd(context);

		ContentResolver cr = context.getContentResolver();
		ContentValues cv = new ContentValues();
		cv.put("CHECKED_COMPANY_CD", companyCd);
		cr.update(Uri.parse("content://com.skt.pe.auth"), cv, null, null);

		Map<String, String> authParam = getGMPAuthPwd(context, mdn, appId);
		if (authParam.get(ID_ENC_PWD) == null)
			throw new Exception("E008");
	}

	public static void updateCheckedCompanyCd(Context context) throws Exception {
		ContentResolver cr = context.getContentResolver();
		ContentValues cv = new ContentValues();
		cv.put("CHECKED_COMPANY_CD", B_COMPANY_CODE);
		cr.update(Uri.parse("content://com.skt.pe.auth"), cv, null, null);
	}

	/**
	 * 코어 어플리케이션 다운로드
	 * 
	 * @param context
	 * @param appIdList
	 */
	public static void installCorePush(final Context context,
			List<String> appIdList) {
		String message;
		String appName = "";
		final List<String> apps = appIdList;

		File file = new File("/sdcard/.installer/apk");

		if (file.exists()) {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				files[i].delete();
			}
		}

		if (apps.size() == 1) {
			appName = getAppName(apps.get(0));
		} else {
			for (int i = 0; i < apps.size(); i++) {
				if (i == 0) {
					appName += getAppName(apps.get(i));
				} else {
					appName += ", " + getAppName(apps.get(i));
				}
			}
		}

		if (appIdList.contains("Z0000PE001")
				|| appIdList.contains("Z000S00002")) {
			// message = appName +" "+
			// context.getResources().getString(R.string._E034);
			message = "test";
			new AlertDialog.Builder(context)
					// .setTitle(R.string.version_update_title)
					.setTitle("test").setMessage(message)
					.setPositiveButton("확인", mGotoInstaller).create().show();
		} else {
			// message = appName +" "+
			// context.getResources().getString(R.string._E034_WEB);
			message = "test";
			new AlertDialog.Builder(context)
					// .setTitle(R.string.version_update_title)
					.setTitle("test").setMessage(message)
					.setPositiveButton("확인", mGotoInstallPage).create().show();
		}
	}

	private static String getAppName(String appId) {
		String name = "";
		if (appId.equals("Z0000PE001")) {
			// name = mContext.getResources().getString(R.string.auth);
		} else if (appId.equals("Z0000PE002")) {
			// name = mContext.getResources().getString(R.string.store);
		} else if (appId.equals("Z000S00002")) {
			// name = mContext.getResources().getString(R.string.resource);
		}
		return name;

	}

	static DialogInterface.OnClickListener mGotoInstallPage = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {

			Intent intent = new Intent(Intent.ACTION_VIEW,
					Uri.parse("http://m.toktok.sk.com"))
					.addCategory(Intent.CATEGORY_BROWSABLE);
			mContext.startActivity(intent);
			((Activity) mContext).finish();
		}
	};

	static DialogInterface.OnClickListener mGotoInstaller = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
			Intent intent = new Intent();
			intent.setComponent(new ComponentName(
					"com.skt.pe.activity.mobileclient",
					"com.skt.pe.activity.mobileclient.CoreAppListActivity"));
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			mContext.startActivity(intent);
			((Activity) mContext).finish();
		}
	};
}
